package com.skivingcloud.admin.sys.service.impl;

import com.skivingcloud.admin.sys.entity.SysStation;
import com.skivingcloud.admin.sys.entity.SysStationMenu;
import com.skivingcloud.admin.sys.entity.SysUserStation;
import com.skivingcloud.admin.sys.entity.User;
import com.skivingcloud.admin.sys.mapper.SysOrgMapper;
import com.skivingcloud.admin.sys.mapper.SysStationMapper;
import com.skivingcloud.admin.sys.mapper.SysStationMenuMapper;
import com.skivingcloud.admin.sys.mapper.SysUserStationMapper;
import com.skivingcloud.admin.sys.service.ISysStationService;
import com.skivingcloud.admin.utils.JacksonJsonUtil;
import com.skivingcloud.common.contants.Constant;
import com.skivingcloud.common.utils.PageUtils;
import com.skivingcloud.common.utils.StringUtils;
import com.skivingcloud.common.utils.TreeUtils;
import com.skivingcloud.common.utils.UuidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONObject;

/**
 * <p>
 * 岗位表 服务实现类
 * </p>
 *
 * @author skivingcloud
 * @since 2022-01-29
 */
@Service
public class SysStationServiceImpl extends ServiceImpl<SysStationMapper, SysStation> implements ISysStationService {

	@Autowired
	private SysOrgMapper sysOrgMapper;
	@Autowired
	private SysStationMenuMapper sysStationMenuMapper;
	@Autowired
	private SysUserStationMapper sysUserStationMapper;
	
	/**
	 * 分页查询岗位数据
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public PageUtils queryPage(Map<String, Object> params) throws Exception {
		PageUtils pageUtils = PageUtils.getPageInfo(params);
		Page<SysStation> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
		String jsonStr = JSONObject.fromObject(params.get("dataForm")).toString();
		SysStation station = (SysStation) JacksonJsonUtil.jsonToObj(new SysStation(), jsonStr);
		QueryWrapper<SysStation> queryWrapper = new QueryWrapper<SysStation>();
		if (station != null) {
			if (StringUtils.isNotBlank(station.getOrgId())) {
				queryWrapper.eq("org_id", station.getOrgId());
			}
			if (StringUtils.isNotBlank(station.getStationName())) {
				queryWrapper.like("station_name", "%" + station.getStationName().trim() + "%");
			}
		}
		queryWrapper.orderByAsc("station_code");
		List<SysStation> list = this.baseMapper.selectList(queryWrapper);
		pageUtils = new PageUtils(p);
		return pageUtils;
	}

	/**
	 * 根据id查询岗位信息
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public SysStation selectById(String id) {
		return this.baseMapper.selectById(id);
	}

	/**
	 * 根据岗位id获取资源权限
	 * 
	 * @param string
	 * @return
	 */
	@Override
	public List<SysStationMenu> getResTreeByStationId(String string) {
		QueryWrapper<SysStationMenu> queryWrapper = new QueryWrapper<SysStationMenu>();
		queryWrapper.eq("station_id", string);
		return sysStationMenuMapper.selectList(queryWrapper);
	}

	/**
	 * 新增岗位
	 * 
	 * @param station
	 * @param user
	 * @param resId
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public void addStation(SysStation station, User user, String[] resId) {
		LocalDateTime nowDate = LocalDateTime.now();
		station.setId(UuidUtil.get32UUID());
		station.setCreater(user.getId());
		station.setCreateTime(nowDate);
		station.setModTime(nowDate);
		station.setModUser(user.getId());
		station.setVersion(0);
		String tenantId = sysOrgMapper.selectById(station.getOrgId()).getTenantId();
		station.setTenantId(tenantId);
		this.baseMapper.insert(station);
		asignStationRes(station.getId(), resId);
	}

	private void asignStationRes(String id, String[] resId) {
		for (String res : resId) {
			SysStationMenu sm = new SysStationMenu();
			sm.setId(UuidUtil.get32UUID());
			sm.setMenuId(res);
			sm.setStationId(id);
			sysStationMenuMapper.insert(sm);
		}
	}

	/**
	 * 修改岗位
	 * 
	 * @param station
	 * @param user
	 * @param resId
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public void updateStation(SysStation station, User user, String[] resId) {
		LocalDateTime nowDate = LocalDateTime.now();
		SysStation record = this.baseMapper.selectById(station.getId());
		record.setVersion(record.getVersion() + 1);
		record.setStationName(station.getStationName());
		record.setShortName(station.getShortName());
		record.setStatus(station.getStatus());
		record.setStationRank(station.getStationRank());
		record.setModUser(user.getId());
		record.setModTime(nowDate);
		this.baseMapper.updateById(record);
		String tenantId = sysOrgMapper.selectById(station.getOrgId()).getTenantId();
		// 先删除角色资源关联再增加，非超级管理员只能删除自己租户的角色资源
		if (user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			QueryWrapper<SysStationMenu> queryWrapper = new QueryWrapper<SysStationMenu>();
			queryWrapper.eq("station_id", station.getId());
			sysStationMenuMapper.delete(queryWrapper);
		} else {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("stationId", station.getId());
			param.put("tenantId", tenantId);
			sysStationMenuMapper.deleteByStationIdAndTenantId(param);
		}
		asignStationRes(station.getId(), resId);
	}

	/**
	 * 仅设置岗位资源
	 * 
	 * @param id
	 * @param resId
	 * @param user
	 */
	@Override
	public void saveStationRes(String id, String[] resId, User user) {
		String tenantId = this.baseMapper.selectById(id).getTenantId();
		// 先删除角色资源关联再增加，非超级管理员只能删除自己租户的角色资源
		if (user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			QueryWrapper<SysStationMenu> queryWrapper = new QueryWrapper<SysStationMenu>();
			queryWrapper.eq("station_id", id);
			sysStationMenuMapper.delete(queryWrapper);
		} else {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("stationId", id);
			param.put("tenantId", tenantId);
			sysStationMenuMapper.deleteByStationIdAndTenantId(param);
		}
		asignStationRes(id, resId);
	}

	/**
	 * 删除岗位信息
	 * 
	 * @param ids
	 */
	@Override
	public void deleteBatch(String[] ids) {
		for (String id : ids) {
			// 删除岗位资源关联
			QueryWrapper<SysStationMenu> queryWrapper = new QueryWrapper<SysStationMenu>();
			queryWrapper.eq("station_id", id);
			sysStationMenuMapper.delete(queryWrapper);
			// 删除岗位用户关联
			QueryWrapper<SysUserStation> queryWrapper1 = new QueryWrapper<SysUserStation>();
			queryWrapper.eq("station_id", id);
			sysUserStationMapper.delete(queryWrapper1);
			this.baseMapper.deleteById(id);
		}
	}

	/**
	 * 批量清除岗位资源权限
	 * 
	 * @param ids
	 * @param user
	 */
	@Override
	public void deleteStationRes(String[] ids, User user) {
		QueryWrapper<SysStationMenu> queryWrapper = new QueryWrapper<SysStationMenu>();
		queryWrapper.in("station_id", Arrays.asList(ids));
		sysStationMenuMapper.delete(queryWrapper);
	}

	/**
	 * 根据租户id获取岗位树
	 * 
	 * @param tenantId
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<TreeUtils> getAllStationTreeUtilsByTenantId(String tenantId) throws Exception {
		if (StringUtils.isBlank(tenantId)) {
			return new ArrayList<TreeUtils>();
		}
		Map<String, Object> paramsNew = new HashMap<String, Object>();
		paramsNew.put("status", Constant.COMMON_STATUS_NORMAL);
		paramsNew.put("tenantId", tenantId);
		List<Map<String, Object>> list = this.baseMapper.getAllStationTreeUtilsByTenantId(paramsNew);
		List<TreeUtils> listTree = TreeUtils.getTreeListMap(list, "id", "parentId", "stationName", "disabledfn",
				"iconfn");
		return listTree;
	}

	/**
	 * 根据租户id获取岗位树，icon属性存的是id
	 * 
	 * @param tenantId
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<TreeUtils> getAllStationTreeUtilsIconFnIdByTenantId(String tenantId) throws Exception {
		if (StringUtils.isBlank(tenantId)) {
			return new ArrayList<TreeUtils>();
		}
		Map<String, Object> paramsNew = new HashMap<String, Object>();
		paramsNew.put("status", Constant.COMMON_STATUS_NORMAL);
		paramsNew.put("tenantId", tenantId);
		List<Map<String, Object>> list = this.baseMapper.getAllStationTreeUtilsByTenantId(paramsNew);
		List<TreeUtils> listTree = TreeUtils.getTreeListMap(list, "id", "parentId", "stationName", "disabledfn", "id");
		return listTree;
	}

}
